package org.apache.lorry.zookeeper.op;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@Slf4j
public class ZkUtil {
    public static final String ROOT_PATH = "/zk_demo";

    public static ZooKeeper getZookeeper(String ipPort, int sessionTimeout, int waitCount, Watcher watcher) throws IOException, InterruptedException {
        ZooKeeper zooKeeper = new ZooKeeper(ipPort, sessionTimeout, watcher);
        ZooKeeper.States zkStates = zooKeeper.getState();
        if(!zkStates.isConnected()){
            for (int i = 1; i < waitCount + 1; i++) {
                log.info("try to connect to zookeeper, wait second = {}s", i);
                TimeUnit.SECONDS.sleep(1);
                boolean connected = zooKeeper.getState().isConnected();
                if (connected) {
                    break;
                }
            }
        }
        try {
            Stat stat = zooKeeper.exists(ROOT_PATH, false);
            if (stat == null) {
                zooKeeper.create(ROOT_PATH, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        } catch (KeeperException e) {
            throw new RuntimeException(e);
        }
        return zooKeeper;
    }
}
